import { Component, OnInit, OnChanges, ElementRef } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { getId } from "utils";

const CLOSE = "CLOSE",
  TOGGLE = "TOGGLE",
  OPEN = "OPEN";

@Component({
  // moduleId: module.id,
  selector: 'dropdown',
  templateUrl: 'dropdown.component.html',
  styleUrls: [
    'dropdown.component.less'
  ],
  inputs: [
    "stock"
  ],
})
export class DropdownComponent implements OnInit, OnChanges {
  stock;
  globalClickSource = Observable.fromEvent(document, "click");
  //一个Subject，控制自身
  //应将此部分抽成directive
  toggleStore = new ReplaySubject().scan((state, action) => {
    switch (action["type"]) {
      case CLOSE:
        return { isShowing: false };
      case OPEN:
        return { isShowing: true };
      case TOGGLE:
        return {
          isShowing: !!!state["isShowing"]
        }
      default: return state;
    }
  }, { isShowing: false });
  $id = getId();

  constructor(private elemRef: ElementRef) {
    let { globalClickSource, $id, toggleStore } = this;
    // 接受全局点击事件，并筛选冒泡链条，确定点击是否来自组件内部；
    // 如果不来自于组件内部，则强制收起菜单
    // 暂时用这种方式实现，如果性能太差，还是直接改成背景蒙版
    globalClickSource.
      filter((e: MouseEvent) =>
        e["path"].every((elem: HTMLElement) =>
          !elem.dataset || elem.dataset["dropdownId"] !== $id)).
      subscribe(() => (this.toggleStore as ReplaySubject<any>).next({
        type: CLOSE
      }));
    // 给组件一个全局唯一ID，并设置为其dataset中的dropdownId参数，反映在dom中即为data-dropdown-id属性
    (elemRef.nativeElement as HTMLElement).dataset["dropdownId"] = $id;
  }
  ngOnChanges(changes) {
    console.debug("Change::::", changes)
  }

  ngOnInit() {
    console.debug("Dropdown Init");
  }

  onClick(e) {
    console.debug("Now Item: ", this.stock);
  }

  toggleClick(stock) {
    console.debug("ToggleClick: ", stock);
    (this.toggleStore as ReplaySubject<any>).next({
      type: TOGGLE
    })
  }

}